package com.app.backend.common.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @program: RedisLock
 * @description: 基于redis的分布式锁
 * @author: Zhun.Xiao
 * @create: 2020-02-07 21:12
 **/

@Slf4j
@Component
public class RedisLock implements DistributeLockTemplate {


    @Autowired
    private RedisLockRegistry redisLockRegistry;

    @Override
    public Object execute(String lockId, int timeout, TimeUnit unit, CallbackDistribute callback) {
        Lock lock = null;
        boolean getLock = false;
        try {
            lock = redisLockRegistry.obtain(lockId);
            getLock = lock.tryLock(timeout, unit);
            if (getLock) {
                return callback.onGetLock();
            } else {
                return callback.onTimeOut();
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        } finally {
            if (getLock) {
                lock.unlock();
            }
        }

        return null;

    }
}